package com.tank.dao.impl;

import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.tank.bean.Notice;
import com.tank.bean.User;
import com.tank.dao.NoticeDAO;
import com.tank.util.Pager;
import com.tank.util.TankUtil;

@Repository("ndao")
public class NoticeDaoImpl extends TankDaoSupport implements NoticeDAO {

	@SuppressWarnings("unchecked")
	public Pager findNoticeList() {
		return  this.getHibernateTemplate().execute(new HibernateCallback<Pager>() {

			public Pager doInHibernate(Session s)
					throws HibernateException, SQLException {
				
				
				User u=TankUtil.getCurrentUser();
				Pager pager=new Pager();
//				Query q=s.createQuery("select n from Notice n where n.target.id=:tid and (n.readtime is null or n.readtime>:dateline) order by n.id desc");
				Query q=s.createQuery("select n from Notice n where n.target.id=:tid and (n.readtime is null ) order by n.id desc");
				q.setInteger("tid", u.getId());
				
				Date dateline=new Date();
				  Calendar calendar = Calendar.getInstance();//日历对象
				  calendar.setTime(dateline);//设置当前日期
				  calendar.add(Calendar.MONTH, -1);//月份减一
				  
				  
				//q.setTimestamp("dateline",calendar.getTime() );
				
				
//				Query qc=s.createQuery("select count(n.id) from Notice n where n.target.id=:tid and (n.readtime is null or n.readtime>:dateline)");
				Query qc=s.createQuery("select count(n.id) from Notice n where n.target.id=:tid and (n.readtime is null)");
				qc.setInteger("tid", u.getId());	
//				qc.setTimestamp("dateline",calendar.getTime() );
				
				pager.setRowCount(qc.uniqueResult());
				pager.setData(pager.pageQuery(q));
				
				s.clear();
				Query q1=s.createQuery("update Notice n set n.readtime=:datenow  where n.target.id=:tid and n.readtime is null");
				q1.setInteger("tid", u.getId());
				Date datenow=new Date();
				System.out.println(datenow);
				q1.setTimestamp("datenow", datenow);
				q1.executeUpdate();
				
				return pager;
			}
		});
	}

	public void save(Notice n) {
		this.getHibernateTemplate().save(n);
	}

	public void remove(final Notice n) {
		this.getHibernateTemplate().execute(new HibernateCallback<Object>() {

			public Object doInHibernate(Session s) throws HibernateException,
					SQLException {
				Query q=s.createQuery("delete Notice n where n.master.id=:mid and n.target.id=:tid and n.type=:type");
				q.setInteger("mid", n.getMaster().getId());
				q.setInteger("tid", n.getTarget().getId());
				q.setString("type", n.getType());
				return q.executeUpdate();
			}
		});
		
	}

}
